﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Atmk.WaterMeter.MIS.Base;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic.WeiXin;
using Atmk.WaterMeter.MIS.Commons.Interfaces.WeiXin;
using Atmk.WaterMeter.MIS.Commons.ViewModels.WeiXin;
using Atmk.WaterMeter.MIS.Controllers.Pay.Base;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace Atmk.WaterMeter.MIS.Controllers.Pay
{
    /// <summary>
    /// 微信平台 登陆Api
    /// </summary>
    public class Wx_AuthenticationController:BaseApiController
    {
        private static ILogger<Wx_AuthenticationController> _Logger;
        private readonly IWxSignService _wxSignService;
        private readonly IWxLogin _wxLogin;
        private readonly IWxAccountLogic _wxAccountLogic;

        /// <inheritdoc />
        public Wx_AuthenticationController(
            IWxSignService wxSignService,
            IWxLogin wxLogin,
            IWxAccountLogic wxAccountLogic,
            ILogger<Wx_AuthenticationController> logger
        )
        {
            _wxSignService = wxSignService;
            _wxLogin = wxLogin;
            _wxAccountLogic = wxAccountLogic;
            _Logger = logger;
        }

        /// <summary>
        /// 登陆
        /// </summary>
        [HttpGet("/api/{X-Version}/pay/wx/login")]
        public async Task<IActionResult> SignIn(string code,string type)
        {
            try
            {
                //通过code获取微信API提供的信息

                var respon = await _wxLogin.LoginCode2Session(WxConfigManage.GetAppid(type), WxConfigManage.GetAppSecret(type), code);
                if(respon.errcode!=0)
                    return Ok(new {respon.errcode, msg = $"登录失败:{respon.errmsg}" });
                //通过openid，获取小程序用户在抄表系统里的账户信息
                var success = await _wxAccountLogic.SelectAccount(respon.openid, out var meterNumber, out var houseNumber,
                    out var balance);
                var account = new WxAccountVm
                {
                    openid = respon.openid,
                    Isbind = success ? 0 : 1,
                    meterNumber = success ? meterNumber : string.Empty,
                    houseNumber = success ? houseNumber : string.Empty,
                    balance = success ? decimal.ToInt32(balance * 100) : -1
                };
                //生成token，整体结果
                var isSuccess = _wxSignService.TryGetToken(respon.openid,respon.session_key, out var token);

                return isSuccess
                    ? Ok(new { errcode = 0, msg = "登录成功", data = new { token, account } })
                    : Ok(new { errcode = 1, msg = "登录失败,Token生成失败" });
            }
            catch (Exception e)
            {
                _Logger.LogError(e.Message, e);
                return Ok(new { errcode = 1, msg = $"登录失败:{e.Message}" });
            }
        }

      
    }
}
